<template>
  <div class="content">
    <canvas ref="cvs" class="canvas" />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted } from 'vue';

const cvs = ref(null);

onMounted(() => {
  const ctx = cvs.value?.getContext('2d');

  //字体大小
  const fontSize = 10 * devicePixelRatio;

  const width = cvs.value?.clientWidth;
  const height = cvs.value?.clientHeight;

  //列宽
  const columnWidth = fontSize;

  //列数
  const columnNum = Math.floor(width / columnWidth) || 0;

  //每一列下个文字下标
  const nextChars = new Array(columnNum).fill(0);
  //绘制
  const draw = () => {
    ctx.fillStyle = 'rgba(0,0,0,0.3)';
    ctx.fillRect(0, 0, width, height);
    for (let i = 0; i < nextChars.length; i++) {
      //获取字符串
      const char = getRandomChar();

      //获取颜色
      ctx.fillStyle = getRandomColor();
      ctx.font = `${fontSize}px "Roboto Mono"`;

      const x = columnWidth * i;
      const y = (nextChars[i] + 1) * fontSize;

      ctx.fillText(char, x, y);

      if (y > height && Math.random() > 0.99) {
        nextChars[i] = 0;
      } else {
        nextChars[i]++;
      }
    }
    requestAnimationFrame(draw);
  };
  requestAnimationFrame(draw);
  // setInterval(draw, 40);
});

//获取随机字符
function getRandomChar() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // 字符集
  const randomIndex = Math.floor(Math.random() * chars.length); // 生成随机索引
  return chars[randomIndex]; // 返回随机字符
}

// 获取随机颜色
function getRandomColor() {
  const letters = '0123456789ABCDEF';
  let color = '#'; // 颜色值以 "#" 开头
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)]; // 随机选取16进制数
  }
  return color;
}
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: calc(100vh - 100px);
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #000;
  .canvas {
    width: 100%;
    height: 100%;
  }
}
</style>
